using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Diagnostics;

namespace SPTraceView
{
    internal class Updater
    {
        //private const string UPDATE_LOCATION = "http://www.hristopavlov.net/SPTraceView/";
        private const string UPDATE_LOCATION = "https://sptraceview.svn.codeplex.com/svn/SPTraceView2007/";
        
        private string m_InstallPath = null;

        public Updater()
        {
            m_InstallPath = AppDomain.CurrentDomain.BaseDirectory;
        }

        public bool NewUpdatesAvailable()
        {
            Trace.WriteLine("Checking for updates ...", "SPTraceView");

            Uri updateUri = new Uri(UPDATE_LOCATION + "Updates.xml");

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(updateUri);
            httpRequest.Method = "GET";
            httpRequest.Timeout = 30000; //30 sec

            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)httpRequest.GetResponse();

                string updateXml = null;

                Stream streamResponse = response.GetResponseStream();

                try
                {
                    using (TextReader reader = new StreamReader(streamResponse))
                    {
                        updateXml = reader.ReadToEnd();
                    }
                }
                finally
                {
                    streamResponse.Close();
                }

                if (updateXml != null)
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(updateXml);

                    int latestVersion = CurrentlyInstalledVersion();

                    foreach (XmlNode updateNode in xmlDoc.SelectNodes("SPTraceView/Update"))
                    {
                        int Version = int.Parse(updateNode.Attributes["Version"].Value);
                        Trace.WriteLine(string.Format("Current version: {0}; Published Version: {1}", VersionToVersionString(latestVersion), VersionToVersionString(Version)), "SPTraceView");
                        if (latestVersion < Version)
                        {
                            return true;
                        }
                    }
                }
            }
            finally
            {
                // Close response
                if (response != null)
                    response.Close();
            }

            return false;
        }

        private int CurrentlyInstalledVersion()
        {
            try
            {
                Version sptvVer = Assembly.GetExecutingAssembly().GetName().Version;
                return 10000 * sptvVer.Major + 1000 * sptvVer.Minor + 100 * sptvVer.Build + sptvVer.Revision;
            }
            catch
            { }

            return 0;
        }

        public static string VersionToVersionString(int version)
        {
            StringBuilder outVer = new StringBuilder();
            outVer.Append(Convert.ToString(version / 10000));
            outVer.Append(".");

            version = version % 10000;
            outVer.Append(Convert.ToString(version / 1000));
            outVer.Append(".");

            version = version % 1000;
            outVer.Append(Convert.ToString(version / 100));
            outVer.Append(".");
            outVer.Append(Convert.ToString(version % 100));

            return outVer.ToString();
        }
    }
}
